# tests.py
from django.test import TestCase
from unittest.mock import patch, MagicMock
from .tasks import insert_data_to_mongodb


class InsertDataToMongoDBTest(TestCase):

    @patch('yourapp.tasks.MongoClient')
    def test_insert_data_to_mongodb(self, mock_client):
        # 设置模拟对象的返回值
        mock_client_instance = mock_client.return_value
        mock_db = mock_client_instance.__getitem__.return_value
        mock_collection = mock_db.__getitem__.return_value
        mock_result = MagicMock()
        mock_result.inserted_id = 'mocked_id'
        mock_collection.insert_one.return_value = mock_result

        # 由于函数中使用了Django settings，你也需要模拟这些设置
        from django.conf import settings
        with self.settings(
                MONGODB_USER='user',
                MONGODB_PASSWORD='pass',
                MONGODB_SERVER='localhost',
                MONGODB_DB='testdb'
        ):
            # 调用待测函数
            insert_data_to_mongodb('test message')

            # 验证MongoClient是否被调用
            mock_client.assert_called_with('mongodb://user:pass@localhost/?authSource=testdb')

            # 验证数据库和集合是否被正确访问
            mock_client_instance.__getitem__.assert_called_with('testdb')
            mock_db.__getitem__.assert_called_with('hello')

            # 验证数据是否被插入
            mock_collection.insert_one.assert_called_once()

            # 如果需要验证日志信息，可以继续使用 MagicMock 来模拟日志器
            # 例如:
            # with patch('yourapp.tasks.logger') as mock_logger:
            #     insert_data_to_mongodb('test message')
            #     mock_logger.info.assert_called_with(f"Inserted document with id {mock_result.inserted_id}")
